from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.utils import dates
from airflow.utils.session import provide_session


class ProjectUser(Base):
    """the class to get user info."""

    __tablename__ = "idata_project_user"
    __table_args__ = {"useexisting": True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    project_id = Column(Integer)
    oa_user_name = Column(String(32))
    create_by = Column(String(32))
    create_time = Column(DateTime)

    def __init__(self, project_id, oa_user_name, create_by, create_time):
        self.project_id = project_id
        self.oa_user_name = oa_user_name
        self.create_by = create_by
        self.create_time = create_time

    @staticmethod
    @provide_session
    def get_project_user_relationship(id, session: Session = None):
        return session.query(ProjectUser).filter(ProjectUser.id == id).first()

    @staticmethod
    @provide_session
    def add_project_user(project_user, session: Session = None):
        result = session.query(ProjectUser)\
            .filter(ProjectUser.project_id == project_user.project_id, ProjectUser.oa_user_name == project_user.oa_user_name)\
            .first()
        if result is None:
            return session.add(project_user)

    @staticmethod
    @provide_session
    def delete_project_user(project_id, oa_username, session: Session = None):
        query = session.query(ProjectUser)
        if project_id != '' and project_id is not None:
            query = query.filter(ProjectUser.project_id == project_id)
        if oa_username != '' and oa_username is not None:
            query = query.filter(ProjectUser.oa_user_name == oa_username)
        query.delete()

    @staticmethod
    @provide_session
    def update_project_user_relationship(project_user_relationship , session: Session = None):
        result = session.query(ProjectUser).filter(ProjectUser.id == project_user_relationship.id).first()
        if result is None:
            return
        else:
            return session.merge(project_user_relationship)

    def to_json(self):
        if self is None:
            return None
        data = {
            'id': self.id,
            'project_id': self.project_id,
            'oa_user_name': self.oa_user_name,
            'create_by': self.create_by,
            'create_time': dates.to_milliseconds(self.create_time),
            'enable': self.enable
        }
        return data
